package dataserver.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.wenhao.jpa.Specifications;
import dataserver.dto.SceneDeviceRelationDTO;
import dataserver.pojo.SceneDevice;
import dataserver.pojo.SceneDeviceRelation;
import dataserver.service.SceneDeviceRelationService;
import dataserver.service.SceneDeviceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lrz
 */
@Controller
@CrossOrigin
@RequestMapping("/deviceRelation")
@Tag(name = "场景设备与系统设备关系管理")
public class SceneDeviceRelationController extends BaseController {
    private static final Logger logger = LogManager.getLogger(SceneDeviceRelationController.class);

    @Autowired
    SceneDeviceRelationService sceneDeviceRelationService;
    @Autowired
    SceneDeviceService sceneDeviceService;

    /**
     * 保存数据
     */
    @Operation(summary = "保存数据")
    @PostMapping()
    public void save(@RequestBody SceneDeviceRelationDTO dto, HttpServletResponse response) throws Exception {
        try {
            if (dto != null) {
                SceneDeviceRelation jsonToBean = new SceneDeviceRelation();
                if (dto.getId() != null) jsonToBean.setId(dto.getId());
                if (dto.getUnrealName() != null) jsonToBean.setUnrealName(dto.getUnrealName());
                if (dto.getEquipmentId() != null) jsonToBean.setEquipmentId(dto.getEquipmentId());
                if (dto.getEquipmentName() != null) jsonToBean.setEquipmentName(dto.getEquipmentName());
                if (dto.getType() != null) jsonToBean.setType(dto.getType());
//                // 将dto转为vo
//                String jsonStr = JSON.toJSONString(dto);
//                // 先转成JSON对象
//                JSONObject jsonObject=JSON.parseObject(jsonStr);
//                // JSON对象转换成Java对象
//                SceneDeviceRelation jsonToBean = jsonObject.toJavaObject((Type) SceneDevice.class);

//                SceneDeviceRelation jsonToBean = JSON.parseObject(jsonStr, (Type) SceneDevice.class);
//                SceneDeviceRelation jsonToBean = (SceneDeviceRelation) JsonUtil.getJsonToBean(dto, SceneDevice.class);
//                jsonToBean.setCreateTime(new Date());
                int t = sceneDeviceRelationService.save(jsonToBean);
                returnCollection(response, 1);
            } else {
                returnCollection(response, 0);
            }
        } catch (Exception e) {
            returnCollection(response, e);
        }
    }

    /**
     * 根据ID删除
     */
    @Operation(summary = "根据ID删除")
    @DeleteMapping(value = "/{id}")
    public void deleteById(@PathVariable String id, HttpServletResponse response) throws Exception {
        try {
            sceneDeviceRelationService.deleteById(id);
            returnCollection(response, 1);
        } catch (Exception e) {
            returnCollection(response, e);
        }
    }

    /**
     * 分页查询
     */
    @Operation(summary = "根据条件分页查询信息")
    @GetMapping(value = "")
    public void findPageData(HttpServletResponse response,
                             @RequestParam(required = false) String stationId,
                             @RequestParam(required = false) String unrealName,
                             @RequestParam(required = false) String type,
                             @RequestParam(required = false, defaultValue = "1") int page,
                             @RequestParam(required = false, defaultValue = "10") int size) throws Exception {
        try {
            // 创建匹配器，需要查询条件请修改此处代码
            Specification<SceneDeviceRelation> specification = Specifications.<SceneDeviceRelation>and()
                    .eq(!StringUtils.isBlank(stationId), "stationId", stationId)
                    .eq(!StringUtils.isBlank(unrealName), "unrealName", unrealName)
                    .eq(!StringUtils.isBlank(type), "type", type)
                    .build();
            Pageable pageable = PageRequest.of(page - 1, size, Sort.Direction.DESC, "stationId");
            Page<SceneDeviceRelation> pageData = sceneDeviceRelationService.findPageData(specification, pageable);
            String targetData = getPageData(pageData);
            returnCollection(response, targetData);
        } catch (Exception e) {
            returnCollection(response, e);
        }
    }

    /**
     *
     */
    @Operation(summary = "根据条件查询信息")
    @GetMapping(value = "/findData")
    public void findData(HttpServletResponse response,
                         @RequestParam(required = false) String stationId,
                         @RequestParam(required = false) String unrealName,
                         @RequestParam(required = false) String type,
                         @RequestParam(required = false) String equipmentId) throws Exception {
        try {
            // 创建匹配器，需要查询条件请修改此处代码
            Specification<SceneDeviceRelation> specification = Specifications.<SceneDeviceRelation>and()
                    .eq(!StringUtils.isBlank(stationId), "stationId", stationId)
                    .eq(!StringUtils.isBlank(unrealName), "unrealName", unrealName)
                    .eq(!StringUtils.isBlank(type), "type", type)
                    .eq(!StringUtils.isBlank(equipmentId), "equipmentId", equipmentId)
                    .build();
            List<SceneDeviceRelation> sourceData = sceneDeviceRelationService.findData(specification);
            // 转dto
            List<SceneDeviceRelationDTO> targetData = new ArrayList<>();
            for (SceneDeviceRelation relation : sourceData) {
                SceneDeviceRelationDTO dto = new SceneDeviceRelationDTO(relation);
                targetData.add(dto);
            }
            returnCollection(response, targetData);
        } catch (Exception e) {
            returnCollection(response, e);
        }
    }

    // 根据条件查询信息
    @Operation(summary = "根据条件查询信息")
    @GetMapping(value = "/findByUnrealName")
    public void findByUnrealName(HttpServletResponse response,
                                 @RequestParam(required = false) String stationId,
                                 @RequestParam(required = false) String type,
                                 @RequestParam(required = false) String unrealName) throws Exception {
        try {
            List<SceneDeviceRelation> sourceData = new ArrayList<>();
            if (!StringUtils.isBlank(unrealName)) {
                sourceData = sceneDeviceRelationService.findByUnrealName(unrealName);
            } else {
                sourceData = sceneDeviceRelationService.findAll();
            }
            returnCollection(response, sourceData);
        } catch (Exception e) {
            returnCollection(response, e);
        }
    }
}
